#!/usr/bin/env perl

# Perl parameter example with Getopt::Long, with stdin piping support.
# License: CC0

# Usage:
# ./param3.pl 'some test text'
# echo 'some test' | ./param3.pl -

# To handle CLI parameters
use Getopt::Long;

# Shows up when --help or -h is passed
sub help_text {
	print("usage: param3.pl [-h] [TEXT]

Prints the text that is passed to it.

optional arguments:
  -h, --help            show this help message and exit

usage:
  Simple example:
    ./param3.pl 'some test'
  Also supports piping the TEXT:
    echo 'some test' | ./param3.pl -\n");
	exit;
}

my $stdio;

# An example subroutine that just prints whatever is passed to it.
sub printit {
	print(shift . "\n");
}

# Process CLI parameters and update config values as necessary
GetOptions ('<>'             => \&printit,
			# $stdio is set to 1 if anything is piped
			''               => \$stdio,
			"h|help"         => \&help_text)
or die("Error in command line arguments. Please review and try again.\n");

# Something is piped via stdin, so handle it
if ($stdio) {
	my $input = <>;
	# Get rid of empty line at the end
	chomp $input;
	printit($input);
}
